package com.cy.milktea.pojo.System;

import com.cy.milktea.mapper.RoleMapper;
import com.cy.milktea.mapper.UserMapper;
import com.cy.milktea.pojo.User;
import org.apache.shiro.authc.*;
import org.apache.shiro.authc.credential.CredentialsMatcher;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;

import java.util.Set;

public class ShiroRealm extends AuthorizingRealm {

    @Autowired
    private UserMapper userMapper;
    @Autowired
    private RoleMapper roleMapper;

    //认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        UsernamePasswordToken upToken = (UsernamePasswordToken) authenticationToken;
        String username = upToken.getUsername();
        //根据username查询user信息
        User user = userMapper.selectByUsername(username);
        //user为空抛出用户不存在异常
        if (user == null) throw new RuntimeException("当前用户不存在!");
        if (user.getValid() == 0) throw new LockedAccountException("当前用户被禁用!");
        //交给认证器进行认证操作
        return new SimpleAuthenticationInfo(
                user,
                user.getPassword(),
                ByteSource.Util.bytes(user.getSalt()),
                this.getName()
        );
    }

    // 设置认证时的加密算法
    @Override
    public CredentialsMatcher getCredentialsMatcher() {
        HashedCredentialsMatcher hcm = new HashedCredentialsMatcher("MD5");
        hcm.setHashIterations(3);
        return hcm;
    }

    //授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        User user = (User) principalCollection.getPrimaryPrincipal();
        Set<String> permissions = roleMapper.selectPermissions(user.getRoleId());
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        //获取当前角色权限
        info.setStringPermissions(permissions);
        return info;
    }
}




















